import { app } from "../../../base";
import { Handler } from "../../../app_base/base/utils/Handler";
import { ILoginAble } from "../../../app_base/module/publisher/ILoginAble";

const wx = window['wx'];
const LoginAPI = "https://api.game.hnquyou.com/api/game-common/user/login";
export class WXLoginHelper extends ILoginAble {
    private _openId: string;
    login(caller?: any, onSuccess?: () => void, onFail?: () => void): void {
        wx.login({
            success: (res: { code: string }) => {
                if (res.code) {
                    // this._code = res.code;
                    app.net.http.post(LoginAPI, {
                        data: {
                            appid: app.publisher.appId,
                            code: res.code,
                            // anonymousCode: res.anonymousCode
                        },
                        onComplete: Handler.create(this, (serverData) => {
                            console.log("openid获取成功:", serverData);
                            if (typeof serverData == 'string' && serverData.length > 0) {
                                serverData = JSON.parse(serverData)
                            }
                            let resData = serverData.data;
                            if (resData) {
                                this._openId = resData.openid || resData.anonymousOpenid;

                                onSuccess && onSuccess.apply(caller);
                            } else {
                                onFail.apply(caller);
                            }
                        })
                    })
                    onSuccess && onSuccess.apply(caller);
                } else {
                    onFail && onFail.apply(caller);
                }
            },
            fail: () => {
                onFail && onFail.apply(caller);
            }
        });
    }

    get openID(): string {
        return this._openId;
    }
}